package kr.hkit.powerjava.chapter18;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JPopupMenu;
import javax.swing.JMenuItem;

import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class PopMenuTest extends JFrame implements ActionListener {

	private JPanel contentPane;
	private JMenuItem mntmNewMenuItem;
	private JMenuItem mntmNewMenuItem_1;
	private JPopupMenu popupMenu;
	private JTextArea textArea;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					PopMenuTest frame = new PopMenuTest();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public PopMenuTest() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		
		textArea = new JTextArea(10,45);
		contentPane.add(textArea);
		
		popupMenu = new JPopupMenu();
		contentPane.add(popupMenu);
		
		mntmNewMenuItem = new JMenuItem("탐색 메뉴");
		mntmNewMenuItem.addActionListener(this);
		popupMenu.add(mntmNewMenuItem);
//		contentPane.add(mntmNewMenuItem);
		
		mntmNewMenuItem_1 = new JMenuItem("저장 메뉴");
		mntmNewMenuItem_1.addActionListener(this);
		popupMenu.add(mntmNewMenuItem_1);
//		contentPane.add(mntmNewMenuItem_1);
		
		textArea.addMouseListener(new PopupListener());
		
	}
	
	class PopupListener extends MouseAdapter {

		@Override
		public void mousePressed(MouseEvent e) {
			showPopup(e);
		}

		@Override
		public void mouseReleased(MouseEvent e) {
			showPopup(e);
		}
		
		private void showPopup(MouseEvent e) {
			if (e.isPopupTrigger()) {
				popupMenu.show(e.getComponent(), e.getX(), e.getY());
			}
		}

	}
	

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == mntmNewMenuItem_1) {
			actionPerformedMntmNewMenuItem_1(e);
		}
		if (e.getSource() == mntmNewMenuItem) {
			actionPerformedMntmNewMenuItem(e);
		}
	}
	private void actionPerformedMntmNewMenuItem_1(ActionEvent e) {
		JOptionPane.showMessageDialog(this, "저장이 선택되었습니다.");
	}

	protected void actionPerformedMntmNewMenuItem(ActionEvent e) {//탐색
		JOptionPane.showMessageDialog(this, "탐색이 선택되었습니다.");
	}
	
}
